using System;
using System.ComponentModel;
using System.Windows.Forms;
using DiceBot.Answerers;
using Meebey.SmartIrc4net;

namespace DiceBot
{
	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();
		}

		private void _enter_Click(object sender, EventArgs e)
		{
			_ircWorker.RunWorkerAsync();
		    _enter.Enabled = false;
		    _quit.Enabled = true;
		}

		private void _quit_Click(object sender, EventArgs e)
		{
			_ircWorker.CancelAsync();
            _enter.Enabled = true;
            _quit.Enabled = false;
		}

		private void _ircWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			Bot _client = new Bot(_ircWorker);
			_client.Answerers.Add(new Dicer());

			if (_client.Connect(StringStubArrayToStringArray(BotConfig.Instance.Servers), BotConfig.Instance.Port))
			{
				_client.Login(BotConfig.Instance.NickName, BotConfig.Instance.RealName);
				foreach (StringStub channel in BotConfig.Instance.Channels)
				{
					_client.Join(channel);
				}
				if (_client.Registered)
				{
					_client.Message(SendType.Message, "NickServ",
					                string.Format("identify {0}", BotConfig.Instance.Password));
				}
				_client.Listen();
			}
			else
			{
				e.Result = false;
				return;
			}
		}

		private static string[] StringStubArrayToStringArray(StringStub[] strings)
		{
			string[] result = new string[strings.Length];

			for (int serverIndex = 0; serverIndex < strings.Length; serverIndex++)
			{
				result[serverIndex] = strings[serverIndex];
			}

			return result;
		}

		private void _applyOptions_Click(object sender, EventArgs e)
		{
			BotConfig.Instance = (BotConfig) _property.SelectedObject;
		}

		private void _declineOptions_Click(object sender, EventArgs e)
		{
			_property.SelectedObject = BotConfig.Instance.Clone();
		}

		private void _tabControl_Selected(object sender, TabControlEventArgs e)
		{
			if (e.TabPage == _optionsTab)
				_property.SelectedObject = BotConfig.Instance.Clone();
		}

		private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
		{
			BotConfig.Instance.Save();
		}
	}
}